package mahan.core.services;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import mahan.data.model.Customer;
import mahan.data.model.Order;
import mahan.data.model.Product;
import mahan.data.model.ShoppingCart;
import mahan.data.mongodb.MahanDB;

import org.json.JSONException;
import org.json.JSONObject;

public class JSONService {
	public enum TYPES {
		ORDER, CART, CUSTOMER, PRODUCT
	}

	protected static Logger log = Logger.getLogger(JSONService.class.getName());

	protected MahanDB mahanDB;

	public JSONService(String host, int port, String dbName) {
		mahanDB = new MahanDB(host, port, dbName);
	}

	public MahanDB db() {
		return mahanDB;
	}

	public Object query(String... args) throws JSONException {
		@SuppressWarnings("rawtypes")
		Map map = new HashMap();
		String type = args[0];
		switch (TYPES.valueOf(type)) {
		case ORDER:
			int id = Integer.valueOf(args[1]);
			Order order = mahanDB.getOrder(id);
			if (order != null)
				map = order.get();
			return new JSONObject(map);
		case CART:
			id = Integer.valueOf(args[1]);
			ShoppingCart cart = mahanDB.getCart(id);

			return cart.json();
		case CUSTOMER:
			id = Integer.valueOf(args[1]);
			Customer cust = mahanDB.getCustomer(id);
			if (cust != null)
				map = cust.get();
			return new JSONObject(map);
		case PRODUCT:
			id = Integer.valueOf(args[1]);
			Product product = mahanDB.getProduct(id);
			if (product != null)
				map = product.get();
			return new JSONObject(map);
		default:
			log.warning("Unknown type:" + type);
			break;
		}
		return null;
	}
}